package com.snailhd.framework.i18n.nacos;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author snailhd
 */
@Slf4j
public class RegisterNacos implements Runnable {

    private final NacosConfig nacosConfig;

    LinkedBlockingQueue<String> queue;

    private boolean nacosRegisterRunning;

    public RegisterNacos(NacosConfig nacosConfig,
                         LinkedBlockingQueue<String> queue,
                         boolean nacosRegisterRunning) {
        this.nacosConfig = nacosConfig;
        this.queue = queue;
        this.nacosRegisterRunning = nacosRegisterRunning;

        log.info("i18n nacos:{}",nacosConfig);
    }

    @Override
    public void run() {
        try {
            String local;
            while (true) {

                if ((local = queue.poll()) != null) {
                    register(local);
                } else {
                    return;
                }
            }
        } catch (Exception e) {
            log.error("nacos i18n register queue execute error",e);
        }
        this.nacosRegisterRunning = false;
    }

    private void register(String locale) {

        NacosResourceBundleMessageSource.REGISTERED
                .put(locale,new NacosResourceBundleMessageSource.RegisterInfo(System.currentTimeMillis()));

        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, nacosConfig.getServerAddr());
        properties.put(PropertyKeyConst.NAMESPACE, nacosConfig.getNamespace());
        properties.put(PropertyKeyConst.USERNAME, nacosConfig.getUsername());
        properties.put(PropertyKeyConst.PASSWORD, nacosConfig.getPassword());
        try {
            ConfigService configService = NacosFactory.createConfigService(properties);
            FileParser fileParser = FileParserFactory.factory(nacosConfig.getDataId(), locale);
            if(fileParser==null){
                log.error("不支持的文件类型：{},{}",nacosConfig.getDataId(),locale);
                return;
            }
            String dataId = fileParser.getDataId();
            String configInfo = configService.getConfig(dataId, nacosConfig.getGroup(), 5000);
            handle(configInfo,  dataId,locale, fileParser);

            log.info("接收到新的国际化配置!配置内容:{}", configInfo);
            configService.addListener(dataId, nacosConfig.getGroup(), new Listener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    log.info("接收到新的国际化配置!配置内容:{}", configInfo);
                    handle(configInfo,  dataId, locale, fileParser);
                }
                @Override
                public Executor getExecutor() {
                    return null;
                }
            });

        } catch (NacosException e) {
            e.printStackTrace();
        }
    }


    private void handle(String text, String dataId,String locale, FileParser fileParser){
        try {
            ConcurrentHashMap<String, String> map = fileParser.parse(text);
            NacosResourceBundleMessageSource.LOCAL_CACHE.put(locale,map);
        } catch (IOException e) {
            log.error("持久化国际化文件异常：dataId:{} => {}",dataId,text,e);
        }
    }




}
